package cc.linker.steplink.crm.merchant.controller;


import cc.linker.steplink.crm.commons.model.PcUserInfo;
import cc.linker.steplink.crm.commons.service.CommonsService;
import cc.linker.steplink.crm.merchanth5.commons.UserInfoUtil;
import cc.linker.steplink.crm.merchant.service.VipCustomerService;
import cc.linker.steplink.crm.merchanth5.pojo.VipCustomerLogPo;
import cc.linker.steplink.crm.merchanth5.service.VipCustomerLogService;
import cc.linker.steplink.crm.response.GlobalException;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cc.linker.steplink.crm.commons.utils.CharUtils.escapeQueryChars;


/**
 * pc端会员卡相关业务
 * @author huhj
 */
@Slf4j
@RestController
@RequestMapping("/merchant/vip")
public class VipCustomerController {

    @Autowired
    private VipCustomerLogService vipCustomerLogService;
    @Autowired
    private VipCustomerService vipCustomerService;
    @Autowired
    private UserInfoUtil userInfoUtil;
    @Autowired
    private CommonsService commonsService;

    /**
     * 获取领取列表
     * @param session
     * @param pageIndex
     * @param pageSize
     * @param startTime
     * @param endTime
     * @param customerName
     * @param customerPhone
     * @param status （1）已退卡,（2）使用中,（3）已过期
     * @return
     */
    @GetMapping("/getlist")
    public PageInfo getList(HttpServletRequest request,
                            @RequestParam(value = "pageIndex", defaultValue = "1", required = false) Integer pageIndex,
                            @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                            @RequestParam(value = "startTime", defaultValue = "", required = false) String startTime,
                            @RequestParam(value = "endTime", defaultValue = "", required = false) String endTime,
                            @RequestParam(value = "customerName", defaultValue = "", required = false) String customerName,
                            @RequestParam(value = "customerPhone", defaultValue = "", required = false) String customerPhone,
                            @RequestParam(value = "status", defaultValue = "", required = false) Integer status,
                            @RequestParam(value = "vipType", defaultValue = "", required = false) Integer vipType
                            ) throws ParseException, UnsupportedEncodingException {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        Map<String, Object> param = new HashMap<>();
        param.put("orgId", orgId);
        param.put("type", 1);
        if(!StringUtils.isEmpty(startTime)){
            param.put("startTime", startTime+" 00:00:00");
        }
        if(!StringUtils.isEmpty(endTime)){
            param.put("endTime", endTime+" 23:59:59");
        }
        if(!StringUtils.isEmpty(customerName)){
            customerName = URLDecoder.decode(customerName.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
            customerName = customerName.replaceAll("%", "/%");
            param.put("customerName", customerName);
        }
        if(!StringUtils.isEmpty(customerPhone)){
            param.put("customerPhone", customerPhone);
        }
        if(!StringUtils.isEmpty(status)){
            param.put("status", status);
        }
        if(!StringUtils.isEmpty(vipType)){
            param.put("vipType", vipType);
        }
        PageHelper.startPage(pageIndex, pageSize);
        return new PageInfo<>(vipCustomerLogService.getVipLogList(param));
    }

    @GetMapping("/exportlist")
    public void exportList(HttpServletRequest request,
                           @RequestParam(value = "startTime", defaultValue = "", required = false) String startTime,
                           @RequestParam(value = "endTime", defaultValue = "", required = false) String endTime,
                           @RequestParam(value = "customerName", defaultValue = "", required = false) String customerName,
                           @RequestParam(value = "customerPhone", defaultValue = "", required = false) String customerPhone,
                           @RequestParam(value = "status", defaultValue = "", required = false) Integer status,
                           @RequestParam(value = "vipType", defaultValue = "", required = false) Integer vipType,
                           HttpServletResponse response
    ) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        Map<String, Object> param = new HashMap<>();
        param.put("orgId", orgId);
        param.put("type", 1);
        if (!StringUtils.isEmpty(startTime)) {
            param.put("startTime", startTime + " 00:00:00");
        }
        if (!StringUtils.isEmpty(endTime)) {
            param.put("endTime", endTime + " 23:59:59");
        }
        if (!StringUtils.isEmpty(customerName)) {
            customerName = URLDecoder.decode(customerName.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
            customerName = customerName.replaceAll("%", "/%");
            param.put("customerName", customerName);
        }
        if (!StringUtils.isEmpty(customerPhone)) {
            param.put("customerPhone", customerPhone);
        }
        if (!StringUtils.isEmpty(status)) {
            param.put("status", status);
        }
        if (!StringUtils.isEmpty(vipType)) {
            param.put("vipType", vipType);
        }

        List<String> listTitles = new ArrayList<>();
        listTitles.add("领卡人");
        listTitles.add("手机号");
        listTitles.add("权益卡");
        listTitles.add("类型");
        listTitles.add("状态");
        listTitles.add("时间");
        List<String> listString = new ArrayList<>();
        listString.add("customerName");
        listString.add("customerPhone");
        listString.add("vipName");
        listString.add("vipTypeDesc");
        listString.add("status");
        listString.add("createTime");

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<Map<String,Object>> list = new ArrayList<>();
        List<VipCustomerLogPo> vipLogList = vipCustomerLogService.getVipLogList(param);
        for(VipCustomerLogPo logPo: vipLogList){
            Map<String,Object> data = new HashMap<>();
            data.put("customerName",logPo.getCustomerName());
            data.put("customerPhone",logPo.getCustomerPhone());
            data.put("vipName",logPo.getVipName());
            data.put("vipTypeDesc",logPo.getVipTypeDesc());
            data.put("status",logPo.getStatus()==1?"使用中":"已退卡");
            data.put("createTime",formatter.format(logPo.getCreateTime()));
            list.add(data);
        }
        String[] title = listTitles.toArray(new String[listTitles.size()]);
        String fileName = "领卡记录";
        String[] strings = listString.toArray(new String[listString.size()]);
        commonsService.excelDownload(list, strings, title, fileName, response);
    }

    /**
     * 获取付费列表
     * @param session
     * @param pageIndex
     * @param pageSize
     * @param startTime
     * @param endTime
     * @param customerName
     * @param customerPhone
     * @param status
     * @return
     */
    @GetMapping("/getpaylist")
    public PageInfo getPayList(HttpServletRequest request,
                            @RequestParam(value = "pageIndex", defaultValue = "1", required = false) Integer pageIndex,
                            @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                            @RequestParam(value = "startTime", defaultValue = "", required = false) String startTime,
                            @RequestParam(value = "endTime", defaultValue = "", required = false) String endTime,
                            @RequestParam(value = "customerName", defaultValue = "", required = false) String customerName,
                            @RequestParam(value = "customerPhone", defaultValue = "", required = false) String customerPhone,
                            @RequestParam(value = "status", defaultValue = "", required = false) Integer status
    ) throws ParseException, UnsupportedEncodingException {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        Map<String, Object> param = new HashMap<>();
        param.put("orgId", orgId);
        param.put("type", 2);
        if(!StringUtils.isEmpty(startTime)){
            param.put("startTime", startTime+" 00:00:00");
        }
        if(!StringUtils.isEmpty(endTime)){
            param.put("endTime", endTime+" 23:59:59");
        }
        if(!StringUtils.isEmpty(customerName)){
            customerName = URLDecoder.decode(customerName.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
            customerName = customerName.replaceAll("%", "/%");
            param.put("customerName", customerName);
        }
        if(!StringUtils.isEmpty(customerPhone)){
            param.put("customerPhone", customerPhone);
        }
        /**
         * 状态：分已退款、退款中、退款失败、可退款、不可退款
         * （1）已退款：发起了退款并且退款已经成功到账
         * （2）退款中：发起了退款等待返回退款状态返回
         * （3）退款失败：发起了退款但退款失败
         * （4）可退款：付费在15天的结算周期内且未进行过退款操作
         * （5）不可退款：结算到期状态切换为不可退款，若到期时正处于退款中则不进行结算并延长结算周期
         */
        if(!StringUtils.isEmpty(status)){
            param.put("payStatus", status);
        }
        PageHelper.startPage(pageIndex, pageSize);
        return new PageInfo<>(vipCustomerLogService.getVipLogList(param));
    }

    @GetMapping("/exportpaylist")
    public void exportPayList(HttpServletRequest request,
                            @RequestParam(value = "startTime", defaultValue = "", required = false) String startTime,
                            @RequestParam(value = "endTime", defaultValue = "", required = false) String endTime,
                            @RequestParam(value = "customerName", defaultValue = "", required = false) String customerName,
                            @RequestParam(value = "customerPhone", defaultValue = "", required = false) String customerPhone,
                            @RequestParam(value = "status", defaultValue = "", required = false) Integer status,
                              HttpServletResponse response
    ) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        Map<String, Object> param = new HashMap<>();
        param.put("orgId", orgId);
        param.put("type", 2);
        if(!StringUtils.isEmpty(startTime)){
            param.put("startTime", startTime+" 00:00:00");
        }
        if(!StringUtils.isEmpty(endTime)){
            param.put("endTime", endTime+" 23:59:59");
        }
        if(!StringUtils.isEmpty(customerName)){
            customerName = URLDecoder.decode(customerName.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
            customerName = customerName.replaceAll("%", "/%");
            param.put("customerName", customerName);
        }
        if(!StringUtils.isEmpty(customerPhone)){
            param.put("customerPhone", customerPhone);
        }
        /**
         * 状态：分已退款、退款中、退款失败、可退款、不可退款
         * （1）已退款：发起了退款并且退款已经成功到账
         * （2）退款中：发起了退款等待返回退款状态返回
         * （3）退款失败：发起了退款但退款失败
         * （4）可退款：付费在15天的结算周期内且未进行过退款操作
         * （5）不可退款：结算到期状态切换为不可退款，若到期时正处于退款中则不进行结算并延长结算周期
         */
        if(!StringUtils.isEmpty(status)){
            param.put("payStatus", status);
        }
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<VipCustomerLogPo> vipLogList = vipCustomerLogService.getVipLogList(param);
        List<Map<String,Object>> list = new ArrayList<>();
        for(VipCustomerLogPo logPo: vipLogList){
            String amountStr = "";
            if(logPo.getAmount() != null && logPo.getIntegral() != null){
                if(logPo.getIntegral()>0 && logPo.getAmount()>0){
                    amountStr = logPo.getAmountStr()+"元+"+logPo.getIntegral()+"积分";
                }else if(logPo.getAmount()>0){
                    amountStr = logPo.getAmountStr()+"元";
                }else{
                    amountStr = logPo.getIntegral()+"积分";
                }
            }else if(logPo.getAmount() == null ){
                amountStr = logPo.getIntegral()+"积分";
            }else {
                amountStr = logPo.getAmountStr()+"元";
            }
            Map<String,Object> data = new HashMap<>();
            data.put("customerName",logPo.getCustomerName());
            data.put("customerPhone",logPo.getCustomerPhone());
            data.put("vipName",logPo.getVipName());
            data.put("vipTypeDesc",logPo.getVipTypeDesc());
            data.put("amountStr",amountStr);
            //0：未退款，1：已退款，2：退款中，3：退款失败，4：不可退款
            String statusStr = "";
            switch (logPo.getRefundState()){
                case 0 :
                    statusStr = "可退款";
                    break;
                case 1 :
                    statusStr = "已退款";
                    break;
                case 2 :
                    statusStr = "退款中";
                    break;
                case 3 :
                    statusStr = "退款失败";
                    break;
                case 4 :
                    statusStr = "不可退款";
                    break;
            }
            data.put("status",statusStr);
            data.put("createTime",formatter.format(logPo.getCreateTime()));
            list.add(data);
        }
        List<String> listTitles = new ArrayList<>();
        listTitles.add("领卡人");
        listTitles.add("手机号");
        listTitles.add("权益卡");
        listTitles.add("类型");
        listTitles.add("支付金额");
        listTitles.add("状态");
        listTitles.add("时间");
        List<String> listString = new ArrayList<>();
        listString.add("customerName");
        listString.add("customerPhone");
        listString.add("vipName");
        listString.add("vipTypeDesc");
        listString.add("amountStr");
        listString.add("status");
        listString.add("createTime");

        String[] title = listTitles.toArray(new String[listTitles.size()]);
        String fileName = "付费记录";
        String[] strings = listString.toArray(new String[listString.size()]);
        commonsService.excelDownload(list, strings, title, fileName, response);
    }

    /**
     * 退卡
     * @param session
     * @param param
     */
    @PostMapping("/refundvip")
    public void refundVip(HttpServletRequest request,@RequestBody Map<String, String> param) throws ParseException {
        if(StringUtils.isEmpty(param.get("id"))){
            throw GlobalException.build("参数错误");
        }
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        param.put("orgId",userinfo.getOrgId());
        vipCustomerLogService.refundVip(param);
    }

    /**
     * 会员卡管理列表
     * @param session
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @GetMapping("/getviplist")
    public PageInfo getVipList(
            HttpServletRequest request,
            @RequestParam(value = "isIntegral", defaultValue = "0", required = false) Integer isIntegral,
            @RequestParam(value = "name", defaultValue = "", required = false) String name,
            @RequestParam(value = "pageIndex", defaultValue = "1", required = false) Integer pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
            Long excludeId,Long integralGoodsId,Integer status
    )
    {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        Map<String, Object> param = new HashMap<>();
        param.put("orgId", orgId);
        param.put("isIntegral", isIntegral);
        param.put("integralGoodsId", integralGoodsId);
        param.put("excludeId", excludeId);
        param.put("status", status);
        param.put("name", escapeQueryChars(name));
        PageHelper.startPage(pageIndex, pageSize);
        return new PageInfo<>(vipCustomerService.getVipList(param));
    }

    /**
     * 所有会员卡管理列表

     * @return
     */
    @GetMapping("/getviplistAll")
    public List<Map<String,Object>> getviplistAll(
            HttpServletRequest request,
            @RequestParam(value = "name", defaultValue = "", required = false) String name
    )
    {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        Map<String, Object> param = new HashMap<>();
        param.put("orgId", orgId);
        try{
            if(!StringUtils.isEmpty(name)){
                name = URLDecoder.decode(name.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
                name = name.replaceAll("%", "/%");
                param.put("name", name);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return vipCustomerService.getVipListAll(param);
    }


    /**
     * 暂停和恢复发卡
     * @param session
     * @param id      vip卡主键ID
     * @param status  0暂停发卡 1恢复发卡
     */
    @GetMapping("/changevipstatus")
    public void changeVipStatus(
            HttpServletRequest request,
            @RequestParam(value = "id") Integer id,
            @RequestParam(value = "status") Integer status
    )
    {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        Map<String, Object> param = new HashMap<>();
        param.put("orgId", orgId);
        param.put("id", id);
        param.put("status", status);
        vipCustomerService.changeVipStatus(param);
    }

    /**
     * 删除 vip
     * @param session
     * @param id
     */
    @GetMapping("/delvip")
    public void delVip(
            HttpServletRequest request,
            @RequestParam(value = "id") Integer id
    )
    {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        Map<String, Object> param = new HashMap<>();
        param.put("orgId", orgId);
        param.put("id", id);
        vipCustomerService.delVip(param);
    }

    /**
     * 新增编辑vip
     * @param session
     * @param param
     */
    @PostMapping("/savevip")
    public void saveVip(
            HttpServletRequest request,
            @RequestBody Map<String, Object> param
    )
    {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        param.put("orgId", orgId);
        vipCustomerService.saveVip(param);
    }

    /**
     * vip详情
     * @param session
     * @param id
     * @return
     */
    @GetMapping("/getvip")
    public Map<String,Object> getVip(
            HttpServletRequest request,
            @RequestParam(value = "id") Integer id
    ){
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        return vipCustomerService.getVip(id,orgId,request);
    }

    /**
     * 退款
     * @param session
     * @param param
     * @param id log表id
     */
    @PostMapping("/refundmoney")
    public void refund(HttpServletRequest request,@RequestBody Map<String, Object> param) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        param.put("orgId",userinfo.getOrgId());
        vipCustomerService.refund(param);
    }

    /**
     * 通联退款回调
     */
    @PostMapping("/refundcallback")
    public void refundCallBack(@RequestBody Map<String, Object> param){
        LOGGER.info("vip退款通联回调参数："+ JSON.toJSONString(param));
    }
}
